import {
	getUserAddress
} from 'apis/farmer/address.js'
export const addressStore = {
	state: {
		addressList: [],
		defaultId: ""
	},
	getters: {
		getUserAddressById: state => id => {
			return state.addressList.filter(item => item.id === id)[0] || null
		},
		getDefaultAddress(state) {
			return state.addressList.filter(item => item.id === state.defaultId)[0] || state.addressList[0] || null
		}
	},
	mutations: {
		removeAddress(state,id){
			state.addressList = state.addressList.filter(item => item.id !== id)
		},
		setDefaultAddress(state,id){
			state.defaultId = id
		},
		setAddressList(state,list){
			if(!list) return null
			// 添加地址列表
			state.addressList = list
			//  设置默认地址的id
			list.forEach(item => {
				if(item && item.isDefault){
					state.defaultId = item.id
				}
			})
			if(!state.defaultId) return state.defaultId = list[0]['id']
		}
	},
	actions: {
		async loadAddress({commit}) {
			const userAddress = await getUserAddress()
			commit("setAddressList",userAddress.data)
		}
	}

}
